from __future__ import with_statement
import contextlib
import urllib
import cgi
import logging

try:
    import json
except ImportError:
    from django.utils import simplejson as json

from secrets import FACEBOOK_APP_ID, FACEBOOK_APP_SECRET

FACEBOOK_GRAPH_URL = 'https://graph.facebook.com/'

def get_with_args(url, args):
    encoded_args = urllib.urlencode(args)
    target_url = url + '?' + encoded_args

    with contextlib.closing(urllib.urlopen(target_url)) as fh:
        return fh.read()

def get_fb_account_info(auth_code, redirect_url):
    args = {
        'client_id': FACEBOOK_APP_ID,
        'client_secret': FACEBOOK_APP_SECRET,
        'code': auth_code,
        'redirect_uri': redirect_url
    }

    raw_response = get_with_args(FACEBOOK_GRAPH_URL + 'oauth/access_token', args)
    logging.debug(raw_response)
    response = cgi.parse_qs(raw_response)

    access_token = response["access_token"][-1]

    raw_profile = get_with_args(FACEBOOK_GRAPH_URL + 'me', {'access_token': access_token})
    profile = json.loads(raw_profile)

    return profile

def get_auth_code(redirect_url):
    args = {
        'client_id': FACEBOOK_APP_ID,
        'redirect_uri': redirect_url,
        'scope': 'email,user_location,user_birthday'
    }

    encoded_args = urllib.urlencode(args)
    target_url = FACEBOOK_GRAPH_URL + 'oauth/authorize?' + encoded_args
    return target_url

